package com.macro.mall.demo.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.es.EsIndexDto;
import com.macro.mall.demo.service.EsIndexService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;


/**
 * @Author：hwh
 * @Description: Elasticsearch Index Controller
 * @name：EsIndexController
 * @Date：2024/10/15 20:32
 */
@RestController
@Validated
@RequestMapping("/esIndex")
public class EsIndexController {

    private static final Logger logger = LoggerFactory.getLogger(EsIndexController.class);

    @Autowired
    private EsIndexService esService;

    /**
     * 创建索引
     * @param esIndexDto 包含索引信息
     * @return CommonResult
     * @throws IOException
     */
    @PostMapping("/creatIndex")
    public CommonResult createIndex(@Validated @RequestBody EsIndexDto esIndexDto) {
        logger.info("开始创建索引，索引信息：{}", esIndexDto);
        esService.createIndex(esIndexDto);
        logger.info("索引创建成功，索引名称：{}", esIndexDto.getIndexName());
        return CommonResult.success("创建成功");
    }

    /**
     * 修改索引
     * @param esIndexDto 包含索引信息
     * @return CommonResult
     */
    @PutMapping("/updIndex")
    public CommonResult updIndex(@Validated @RequestBody EsIndexDto esIndexDto) {
        logger.info("开始修改索引，索引信息：{}", esIndexDto);
        esService.updIndex(esIndexDto);
        logger.info("索引修改成功，索引名称：{}", esIndexDto.getIndexName());
        return CommonResult.success("修改成功");
    }

    /**
     * 查询索引信息
     * @param indexName 索引名称
     * @return CommonResult
     */
    @GetMapping("/getInfo")
    public CommonResult getInfo( @RequestParam String indexName) {
        logger.info("开始查询索引信息，索引名称：{}", indexName);
        Map<String, Object> map = esService.getInfo(indexName);
        logger.info("索引信息查询成功，索引名称：{}，返回信息：{}", indexName, map);
        return CommonResult.success(map);
    }

    /**
     * 删除索引
     * @param indexName 索引名称
     * @return CommonResult
     */
    @DeleteMapping("/delIndex")
    public boolean delIndex( @RequestParam String indexName) {
        logger.info("开始删除索引，索引名称：{}", indexName);
        esService.delIndex(indexName);
        logger.info("索引删除成功，索引名称：{}", indexName);
        return true;
    }
}

